package handlers

import (
	"2y7zk/api/request"
	"2y7zk/api/response"
	"2y7zk/dao"
	"2y7zk/models"
	"2y7zk/util"
	"github.com/gin-gonic/gin"
	jwt "github.com/golangblogs/gojwt"
	"gorm.io/gorm"
)

func Login(c *gin.Context) {
	var data request.Login
	if err := c.ShouldBind(&data); err != nil {
		response.ResponseDataError(c, err.Error())
		return
	}
	user, err := dao.GetUser(data.Phone)
	if err != nil {
		response.ResponseDataError(c, "查询失败")
		return
	}
	if user.Phone == "" {
		m := models.User{
			Phone:    data.Phone,
			Password: util.PwdMd5(data.Password),
		}
		err := dao.Create(m)
		if err != nil {
			response.ResponseDataError(c, "注册失败")
			return
		}
	}
	if user.Password != util.PwdMd5(data.Password) {
		response.ResponseDataError(c, "密码错误")
		return
	}
	claims := jwt.CustomClaims{ID: user.ID}
	token, err := jwt.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		response.ResponseDataError(c, "token生成失败")
		return
	}
	response.ResponseDataSuccess(c, token)
}

func UserList(c *gin.Context) {
	list, err := dao.UserList()
	if err != nil {
		response.ResponseDataError(c, "查询失败")
		return
	}
	var userList []*models.User
	for _, user := range list {
		userList = append(userList, &models.User{
			Model:    gorm.Model{ID: user.ID},
			Phone:    user.Phone,
			Password: user.Password,
		})
	}
	response.ResponseDataSuccess(c, userList)
}
func List(c *gin.Context) {
	list, err := dao.List()
	if err != nil {
		response.ResponseDataError(c, "查询失败")
		return
	}
	var lists []*models.Message
	for _, message := range list {
		lists = append(lists, &models.Message{
			Model:      gorm.Model{ID: message.ID},
			FormUserId: message.FormUserId,
			ToUserId:   message.ToUserId,
			RoomId:     message.RoomId,
			Message:    message.Message,
		})
	}
	response.ResponseDataSuccess(c, lists)
}
